<template>
  <view class="system_set">
    <leeLoading :animateTxt="leeLoading.animateTxt" :type="leeLoading.type" :shadowBg="leeLoading.shadowBg" :show="leeLoading.show"></leeLoading>
    <scroll-view class="scroll-list" scroll-y="true" :style="'height:'+ clientHeight+'px'">
      <o-cell border card>
        <o-cell-item v-for="(item,index) in systemSetList" :key="index" title-width="470rpx" :title="item.text"
          :value="item.value" @tap="setValue(item.id,item.value,item.text)" />
      </o-cell>
      <view class="uni-list">
        <view class="uni-list-cell uni-list-cell-pd" v-for="(item,index) in systemBtnList" :key="index">
          <view class="uni-list-cell-db">{{item.text}}</view>
          <switch :checked="item.value==1?true:false" @change="isRendering?'':onChange(item.id,item.value)" />
        </view>
      </view>
    </scroll-view>
    <uni-popup ref="popup" background-color="#fff">
      <view class="parameterSet">
        <view class="setText">{{currentText}}</view>
        <slider :value="currentValue" @change="sliderChange" :min="min" :max="max" show-value activeColor="#22b229" />
        <view class="addAndMinus">
          <image class="Temp_minus" @tap="isRendering?'':TempMinus()"
            src="https://mkservice.mk-iot.com/subFile/mk2240/del.png" />
          <image class="Temp_add" @tap="isRendering?'':TempAdd()"
            src="https://mkservice.mk-iot.com/subFile/mk2240/add.png" />
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
 const CmdType = {
    DeviceTime: 10,
    InnerReference: 12
 }
 const CLOSE = 0;
  import leeLoading from '../components/StarLee-loading/leeLoading.vue';
  import {
    toast
  } from '../../utils/common';

  import parsingData from '../util/parsingData'
  import {
    MQTT_IP,
    MQTT_OPTIONS
  } from '@/utils/mqtt.js';
  
  import getdateTime from '../../utils/getdateTime';
  import getPrefixAndControl from '../util/getPrefixAndControl'
  export default {
    components: {
      leeLoading
    },
    data() {
      return {
        leeLoading:{
          show:false,
          type:'rotate3',
          shadowBg:'',
          animateTxt:true
        },
        indexAllData:null,
        isRendering: false, //是否下发时
        equipmentNo:uni.getStorageSync("equipmentNo"),//uni.getStorageSync("equipmentNo"),
        equipmentTypeId:uni.getStorageSync("equipmentTypeId"),//uni.getStorageSync("equipmentTypeId"),
        systemSetList: [],
        systemBtnList: [],
        show: false,
        realTime: null,
        timers:null,
        timeout:null,
        min: 0,
        max: 100,
        currentValue: 0,
        currentText: '',
        listIndex: 0,
        type: 'bottom',
        client: null,
        clientMessage: "",
        subTopic: uni.getStorageSync("subTopic"),
      }
    },
  onShow() {
   //延迟一秒钟去获取数据
   uni.showLoading({title:"数据加载中...", mask:true})
   setTimeout(async () => {
    this.getIndexData()
     //链接mqtt
     this.connect()
   }, 1000);
   //15秒后没关闭就自动关闭
    this.timers= setTimeout(() => {
       uni.hideLoading();
     }, 15000);
    },
    // 组件销毁时关闭定时器
    beforeDestroy() {
      clearTimeout(this.timers)
    },
    methods: {
      getIndexData(){
        this.realTime = setInterval(async () => {
          //下发0x0f获取预约0x07周期
          //进入界面链接mqtt后自动订阅
        const success = await getPrefixAndControl.getConfigList(this.equipmentTypeId, this.equipmentNo, CmdType
          .DeviceTime)
        if (success.code != 200) {
          this.$modal.msgError("下发失败");
        }
        }, 2000);
        },
      //链接方法
      connect() {
            try{
              const thant = this
                this.client = new Paho.Client(MQTT_IP, "SERVER_" + Math.floor(Math.random() * 999) + 1+"_"+thant.equipmentNo)
                //后面这个字符串可以用一个随机字符串方法随机生成
                var connectOptions = {
                  timeout: MQTT_OPTIONS.timeout,
                  useSSL: MQTT_OPTIONS.useSSL,
                  cleanSession: MQTT_OPTIONS.cleanSession, //实现QoS>0必须设置为false，代表不清除，是持久会话
                  keepAliveInterval: MQTT_OPTIONS.keepAliveInterval,
                  reconnect: MQTT_OPTIONS.reconnect, //意外断开之后会重连，第一次1秒后重连，往后每次翻倍直到2分钟，后续保持2分钟
                  mqttVersion: MQTT_OPTIONS.mqttVersion,
                  userName: MQTT_OPTIONS.username,
                  password: MQTT_OPTIONS.password,
                  onSuccess: function() {
                    thant.client.onMessageArrived = function(msg) {
                      const data = JSON.parse(msg.payloadString.replace(/\u0000*$/, ''))
                      if (data != null) {
                        //所有接收的消息都在这里，相关消息的业务处理都写在这里
                        data.Data.forEach((item, index) => {
                          if (item.Cmd == 9) {
                           thant.indexAllData = parsingData.getNumBycommand(item.Cmd, item.Value)
                           if(thant.indexAllData.communicationState!=1){
                             thant.$modal.msgError("通讯错误");
                            clearInterval(this.realTime)
                            uni.stopPullDownRefresh()
                            uni.hideLoading({
                              noConflict:true
                            })
                            return;
                           }
                           if(thant.indexAllData.connt==false){
                               thant.$modal.msg("设备订阅已断开，请重启设备");
                               clearInterval(this.realTime)
                               uni.stopPullDownRefresh()
                               uni.hideLoading({
                                 noConflict:true
                               })
                              return;
                           }
                         }
                          if (item.Cmd == 12) {
                            const NumBycommandData = parsingData.getNumBycommand(item.Cmd, item.Value)
                            thant.systemSetList = [{
                             id: 1,
                             text: '最高温度锁定(-30~60℃)',
                             value: NumBycommandData.freeAndStorageHighTemp
                           },
                           {
                             id: 2,
                             text: '最低温度锁定(-30~60℃)',
                             value: NumBycommandData.freeAndStorageLowTemp
                           },
                           {
                             id: 3,
                             text: '温度修正(-20~20℃)',
                             value: NumBycommandData.tempCorrect
                           },
                           {
                             id: 4,
                             text: '温度控制回差(1~20℃)',
                             value: NumBycommandData.tempControlDifference
                           },
                           {
                             id: 5,
                             text: '温度上收敛(0~5℃)',
                             value: NumBycommandData.tempUpConvergence
                           },
                           {
                             id: 6,
                             text: '温度下收敛(0~5℃)',
                             value: NumBycommandData.tempDownConvergence
                           },
                           {
                             id: 7,
                             text: '照明切换(-1:切换,0:长按,延时:1~120S)',
                             value: NumBycommandData.lightDelay
                           },
                           {
                             id: 8,
                             text: '醒发周期(30~60S)',
                             value: NumBycommandData.proofWeek
                           },
                           {
                             id: 9,
                             text: '醒发加热时间(2~30S)',
                             value: NumBycommandData.proofHeatTime
                           },
                           {
                             id: 10,
                             text: '醒发最高温度(5~60℃)',
                             value: NumBycommandData.proofHighTemp
                           },
                           {
                             id: 11,
                             text: '醒发最低温度(5~60℃)',
                             value: NumBycommandData.proofLowTemp
                           },
                           {
                             id: 12,
                             text: '湿度校正(-30~30%)',
                             value: NumBycommandData.humidityCheck
                           },
                           {
                             id: 13,
                             text: '喷蒸汽关时间(50~1200S)',
                             value: NumBycommandData.steamEtime
                           },
                           {
                             id: 14,
                             text: '喷蒸汽开时间(1~1000S)',
                             value: NumBycommandData.steamStime
                           },
                           {
                             id: 15,
                             text: '湿度回差(1~20%)',
                             value: NumBycommandData.humidityDifference
                           },
                           {
                             id: 16,
                             text: '湿度上收敛(0~50%)',
                             value: NumBycommandData.humidityUpConvergence
                           },
                           {
                             id: 17,
                             text: '湿度下收敛(0~50%)',
                             value: NumBycommandData.humidityDownConvergence
                           },
                           {
                             id: 18,
                             text: '除霜时间(0~99分)',
                             value: NumBycommandData.defrostTime
                           },
                           {
                             id: 19,
                             text: '除霜周期(0~24h)',
                             value: NumBycommandData.defrostWeek
                           },
                           {
                             id: 20,
                             text: '除霜开始温度(-20~1℃)',
                             value: NumBycommandData.defrostSTemp
                           },
                           {
                             id: 21,
                             text: '除霜结束温度(1~20℃)',
                             value: NumBycommandData.defrostETemp
                           },
                           {
                             id: 22,
                             text: '压缩机最长运行时间(0~720分)',
                             value: NumBycommandData.compressorLongRunTime
                           },
                           {
                             id: 23,
                             text: '压缩机降温时间(0~60分)',
                             value: NumBycommandData.compressorLowTempTime
                           },
                           {
                             id: 24,
                             text: '压缩机启动延时(0~60S)',
                             value: NumBycommandData.compressorFiringDelayed
                           },
                           {
                             id: 25,
                             text: '显示亮度(1~63)',
                             value: NumBycommandData.displayLight
                           },
                           {
                             id: 26,
                             text: '高温报警温度(20~70℃)',
                             value: NumBycommandData.highTemperatureAlarm
                           },
                           {
                             id: 27,
                             text: '曲线结束后控制模式(0~3)',
                             value: NumBycommandData.curveEMode
                           },
                           {
                             id: 28,
                             text: '湿度控制校正(-20~20%)',
                             value: NumBycommandData.humidityControlCheck
                           },
                           {
                             id: 29,
                             text: '醒发压缩机启动温度(0~20℃)',
                             value: NumBycommandData.proofOverTemp
                           },
                           {
                             id: 30,
                             text: '喷雾加热开时间(0~100S)',
                             value: NumBycommandData.atomizingHeatSTime
                           },
                           {
                             id: 31,
                             text: '喷雾加热关时间(0~100S)',
                             value: NumBycommandData.atomizingHeatETime
                           },
                           {
                             id: 32,
                             text: '湿度达到后喷雾时间(0~300S)',
                             value: NumBycommandData.humidityReachAtomizingTime
                           },
                           {
                             id: 33,
                             text: '风机开时间(0~100S)',
                             value: NumBycommandData.fanSTime
                           },
                           {
                             id: 34,
                             text: '风机关时间(0~100S)',
                             value: NumBycommandData.fanETime
                           },
                         ]
                         thant.systemBtnList = [{
                           id: 1,
                           text: '蒸汽模式(0:煮水,1:喷水)',
                           value: NumBycommandData.steamMode
                         }, {
                           id: 2,
                           text: '按键声音(0~1)',
                           value: NumBycommandData.keyTone
                         }, {
                           id: 3,
                           text: '除霜时风机运行模式(0~1)',
                           value: NumBycommandData.defrostFanMode
                         }, {
                           id: 4,
                           text: '加热方式(0~1)',
                           value: NumBycommandData.heatMethod
                         },{
                           id: 5,
                           text: '除霜时压缩机是否工作(0~1)',
                           value: NumBycommandData.relWork
                         }]
                          }
                          if (thant.systemSetList.length>0 &&
                            thant.systemBtnList.length>0) {
                            thant.empty()
                            uni.hideLoading();
                          }
                        })
                      }
                    }
                    thant.client.subscribe(thant.subTopic, {
                      qos: 1
                    });
                  },
                  onFailure: function(option) {
                    uni.showToast({
                      title: option,
                      icon: "error",
                    });
                  }
                }
                this.client.connect(connectOptions)
              } catch (error) {
                this.$modal.msgError("连接错误");
              }
      },
      //点击打开弹框
      setValue(id, value, text) {
        this.listIndex = id
        this.$refs.popup.open(this.type)
        switch (id) {
          case 1:
            this.changeSilderValue(60, -30, value, text)
            break;
          case 2:
            this.changeSilderValue(60, -30, value, text)
            break;
          case 3:
            this.changeSilderValue(20, -20, value, text)
            break;
          case 4:
            this.changeSilderValue(20, 1, value, text)
            break;
          case 5:
            this.changeSilderValue(5, 0, value, text)
            break;
          case 6:
            this.changeSilderValue(5, 0, value, text)
            break;
          case 7:
            this.changeSilderValue(120, -1, value, text)
            break;
          case 8:
            this.changeSilderValue(60, 30, value, text)
            break;
          case 9:
            this.changeSilderValue(30, 2, value, text)
            break;
          case 10:
            this.changeSilderValue(60, 5, value, text)
            break;
          case 11:
            this.changeSilderValue(60, 5, value, text)
            break;
          case 12:
            this.changeSilderValue(30, -30, value, text)
            break;
          case 13:
            this.changeSilderValue(1200, 50, value, text)
            break;
          case 14:
            this.changeSilderValue(1000, 1, value, text)
            break;
          case 15:
            this.changeSilderValue(20, 1, value, text)
            break;
          case 16:
            this.changeSilderValue(50, 0, value, text)
            break;
          case 17:
            this.changeSilderValue(50, 0, value, text)
            break;
          case 18:
            this.changeSilderValue(99, 0, value, text)
            break;
          case 19:
            this.changeSilderValue(24, 0, value, text)
            break;
          case 20:
            this.changeSilderValue(1, -20, value, text)
            break;
          case 21:
            this.changeSilderValue(20, 1, value, text)
            break;
          case 22:
            this.changeSilderValue(720, 0, value, text)
            break;
          case 23:
            this.changeSilderValue(60, 0, value, text)
            break;
          case 24:
            this.changeSilderValue(60, 0, value, text)
            break;
          case 25:
            this.changeSilderValue(63, 1, value, text)
            break;
          case 26:
            this.changeSilderValue(70, 20, value, text)
            break;
          case 27:
            this.changeSilderValue(3, 0, value, text)
            break;
          case 28:
            this.changeSilderValue(20, -20, value, text)
            break;
          case 29:
            this.changeSilderValue(20, 0, value, text)
            break;
          case 30:
            this.changeSilderValue(100, 0, value, text)
            break;
          case 31:
            this.changeSilderValue(100, 0, value, text)
            break;
          case 32:
            this.changeSilderValue(300, 0, value, text)
            break;
          case 33:
            this.changeSilderValue(100, 0, value, text)
            break;
          case 34:
            this.changeSilderValue(100, 0, value, text)
            break;
        }
      },
      //改变数据公共方法
      changeSilderValue(max, min, value, text) {
        this.max = max
        this.min = min
        this.currentValue = value
        this.currentText = text
      },
      //滑动滑块变化事件
      sliderChange(e) {
        const values = e.detail.value
        this.determineTemp(values)
      },
      //发布参数设置下发公共方法
      commonSetSystem:async function() {
        switch (this.listIndex) {
          case 1:
            this.systemSetList[0].value = this.currentValue
            break;
          case 2:
            this.systemSetList[1].value = this.currentValue
            break;
          case 3:
            this.systemSetList[2].value = this.currentValue
            break;
          case 4:
            this.systemSetList[3].value = this.currentValue
            break;
          case 5:
            this.systemSetList[4].value = this.currentValue
            break;
          case 6:
            this.systemSetList[5].value = this.currentValue
            break;
          case 7:
            this.systemSetList[6].value = this.currentValue
            break;
          case 8:
            this.systemSetList[7].value = this.currentValue
            break;
          case 9:
            this.systemSetList[8].value = this.currentValue
            break;
          case 10:
            this.systemSetList[9].value = this.currentValue
            break;
          case 11:
            this.systemSetList[10].value = this.currentValue
            break;
          case 12:
            this.systemSetList[11].value = this.currentValue
            break;
          case 13:
            this.systemSetList[12].value = this.currentValue
            break;
          case 14:
            this.systemSetList[13].value = this.currentValue
            break;
          case 15:
            this.systemSetList[14].value = this.currentValue
            break;
          case 16:
            this.systemSetList[15].value = this.currentValue
            break;
          case 17:
            this.systemSetList[16].value = this.currentValue
            break;
          case 18:
            this.systemSetList[17].value = this.currentValue
            break;
          case 19:
            this.systemSetList[18].value = this.currentValue
            break;
          case 20:
            this.systemSetList[19].value = this.currentValue
            break;
          case 21:
            this.systemSetList[20].value = this.currentValue
            break;
          case 22:
            this.systemSetList[21].value = this.currentValue
            break;
          case 23:
            this.systemSetList[22].value = this.currentValue
            break;
          case 24:
            this.systemSetList[23].value = this.currentValue
            break;
          case 25:
            this.systemSetList[24].value = this.currentValue
            break;
          case 26:
            this.systemSetList[25].value = this.currentValue
            break;
          case 27:
            this.systemSetList[26].value = this.currentValue
            break;
          case 28:
            this.systemSetList[27].value = this.currentValue
            break;
          case 29:
            this.systemSetList[28].value = this.currentValue
            break;
          case 30:
            this.systemSetList[29].value = this.currentValue
            break;
          case 31:
            this.systemSetList[30].value = this.currentValue
            break;
          case 32:
            this.systemSetList[31].value = this.currentValue
            break;
          case 33:
            this.systemSetList[32].value = this.currentValue
            break;
          case 34:
            this.systemSetList[33].value = this.currentValue
            break;
        }
          //点击开启加载
          this.loadingClick()
         const res =  await getPrefixAndControl.controlCmd(this.equipmentTypeId, this.equipmentNo, CmdType.InnerReference, this.getSystemSetArray())
        if (res.code!=200) {
         this.$modal.msgError("下发失败");
        }
      },
      
      //点击按钮切换事件
      onChange:async function(index, value) {
        //防止重复点击
        this.preventClick(this.isRendering)
        if (index == 1) {
          this.systemBtnList[0].value = this.systemBtnList[0].value == 1 ? 0 : 1
        } else if (index == 2) {
          this.systemBtnList[1].value = this.systemBtnList[1].value == 1 ? 0 : 1
        } else if (index == 3) {
          this.systemBtnList[2].value = this.systemBtnList[2].value == 1 ? 0 : 1
        } else if (index == 4){
          this.systemBtnList[3].value = this.systemBtnList[3].value == 1 ? 0 : 1
        }else{
           this.systemBtnList[4].value = this.systemBtnList[4].value == 1 ? 0 : 1
        }
        //点击开启加载
        this.loadingClick()
       const res =  await getPrefixAndControl.controlCmd(this.equipmentTypeId, this.equipmentNo, CmdType.InnerReference,this.getSystemSetArray())
       if (res.code!=200) {
        this.$modal.msgError("下发失败");
       }
      },
      //温度值+1
      TempAdd() {
        if (this.currentValue + 1 > this.max) {
            toast("不能高于设置的最大值")
        } else {
          this.preventClick(this.isRendering)
            const values = this.currentValue + 1
            this.determineTemp(values)
        }
      },
      //温度值-1
      TempMinus() {
        if (this.currentValue - 1 < this.min) {
          toast("不能低于设置的最小值")
        } else {
          this.preventClick(this.isRendering)
          const values = this.currentValue-1
          this.determineTemp(values)
        }
      },
        //下发公共数据方法
        getSystemSetArray: function () {
          let systemSetData={
            HTp: this.systemSetList[0].value,
            LTp: this.systemSetList[1].value,
            TpCor:this.systemSetList[2].value,
            TpCon:this.systemSetList[3].value ,
            TpUp:this.systemSetList[4].value,
            TpDw:this.systemSetList[5].value,
            Steam:this.systemBtnList[0].value,
            Light:this.systemSetList[6].value ,
            ProCyc:this.systemSetList[7].value,
            ProHt: this.systemSetList[8].value,
            ProHTp:this.systemSetList[9].value,
            ProLTp:this.systemSetList[10].value,
            Buzz:this.systemBtnList[1].value,
            HmCor: this.systemSetList[11].value,
            SpONT: this.systemSetList[12].value,
            SpOFFT:this.systemSetList[13].value,
            HmDiff:this.systemSetList[14].value,
            HmUp:this.systemSetList[15].value,
            HmDw:this.systemSetList[16].value,
            DefT:this.systemSetList[17].value,
            DefCyc:this.systemSetList[18].value,
            DefSTp:this.systemSetList[19].value,
            DefETp:this.systemSetList[20].value,
            DefFen:this.systemBtnList[2].value,
            ComRunT:this.systemSetList[21].value,
            ComColT:this.systemSetList[22].value,
            ComDey:this.systemSetList[23].value,
            Bright:this.systemSetList[24].value,
            HTpWarn:this.systemSetList[25].value,
            CurCon:this.systemSetList[26].value,
            HmCon: this.systemSetList[27].value,
            ComSTp:this.systemSetList[28].value,
            HtONT:this.systemSetList[29].value,
            HtOFFT:this.systemSetList[30].value,
            SpT: this.systemSetList[31].value,
            FenONT:this.systemSetList[32].value,
            FenOFFT:this.systemSetList[33].value,
            HtMode:this.systemBtnList[3].value,
            RelWork:this.systemBtnList[4].value
          }
          return systemSetData;
        },
      //防止多次点击共用方法
      preventClick(isClick) {
        if (!isClick) {
          this.isRendering = true
          setTimeout(() => {
            this.isRendering = false
          }, 500);
        }
      },
      loadingClick(){
       const thant = this
       thant.leeLoading.show=true
       thant.timeout = setTimeout(function () {
         thant.leeLoading.show=false
         thant.$modal.msgError("操作未成功");
         }, 5000);
       },
      //判断最低和最高温度不能相互低于和高于
      determineTemp(values){
        switch (this.listIndex) {
        case 1:
        if(values <= this.systemSetList[1].value){
            toast("最高温度锁定不能低于或等于最低温度锁定")
        }else{
            this.currentValue =values
            this.commonSetSystem()
        }
        break;
        case 2:
        if(values >= this.systemSetList[0].value){
            toast("最低温度锁定不能高于或等于最高温度锁定")
        }else{
           this.currentValue =values
          this.commonSetSystem()
        }
         break;
        case 10:
        if(values <= this.systemSetList[10].value){
            toast("醒发最高温度不能低于或等于醒发最低温度")
        }else{
           this.currentValue =values
          this.commonSetSystem()
        }
         break;
        case 11:
        if(values >= this.systemSetList[9].value){
            toast("醒发最低温度不能高于或等于醒发最高温度")
        }else{
          this.currentValue =values
          this.commonSetSystem()
        }
        break;
        default:
        this.currentValue =values
         this.commonSetSystem()
          break;
         }
      },
      empty(){
        clearInterval(this.realTime)
        clearTimeout(this.timeout)
        this.leeLoading.show=false
        uni.stopPullDownRefresh()
      }
    },
    onUnload() {
       clearInterval(this.realTime)
       clearTimeout(this.timers)
      if (this.client != null) {
       this.client.disconnect();
       this.client = null;
      }
    },
    //下拉刷新
      onPullDownRefresh() {
         this.systemBtnList =[]
         this.systemSetList =[]
         clearInterval(this.realTime)
         clearTimeout(this.timers)
         this.$modal.loading("数据加载中...");
         this.getIndexData()
      }
  }
</script>

<style>
  page {
    background-color: #F6f6f6;
  }

  .custom-button {
    background-color: rgb(34, 149, 178);
    color: #fff;
    height: 50rpx;
    width: 65rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    padding-top: 10rpx;
    text-align: center;
  }

  .addAndMinus {
    display: flex;
    justify-content: space-between;
    margin-top: 50rpx;
  }

  .Temp_add {
    width: 60rpx;
    height: 60rpx;
  }

  .Temp_minus {
    width: 60rpx;
    height: 60rpx;
  }

  .parameterSet {
    margin: 50rpx auto;
    width: 80%;
  }

  .setText {
    margin-bottom: 40rpx;
    text-align: center;
  }

  .uni-list {
    background-color: #fff;
    position: relative;
    width: 95%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    border-radius: 20rpx;
  }

  .uni-list-cell-pd {
    padding: 11px 15px;
  }

  .uni-list-cell {
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .uni-list-cell-db,
  .uni-list-cell-right {
    flex: 1;
  }
</style>